﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;

namespace TK.Common.AspNetCore
{
    /// <summary>
    /// Extension method used to add the middleware to the HTTP request pipeline.
    /// </summary>
    public static class HealthMiddlewareExtensions
    {
        /// <summary>
        /// 心跳检测
        /// </summary>
        public static IApplicationBuilder UseHealthMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<HealthMiddleware>();
        }
    }

    /// <summary>
    /// 服务监控
    /// </summary>
    public class HealthMiddleware
    {
        private readonly RequestDelegate _next;

        /// <inheritdoc />
        public HealthMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <inheritdoc />
        public async Task Invoke(HttpContext httpContext)
        {
            if (httpContext.Request.Path.HasValue && "/health".Equals(httpContext.Request.Path.Value.TrimEnd('/').ToLower()))
            {
                //心跳检测
                await httpContext.Response.WriteAsync(DateTimeOffset.Now.ToString("F"));
                return;
            }

            await _next(httpContext);
        }
    }
}